#include "TcpSocket.h"
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h> //posix网络编程
#include <iostream>
using namespace std;

typedef struct sockaddr_in sockaddr_in;
typedef struct sockaddr sockaddr;

TcpSocket::TcpSocket()
{
    this->connFd=socket(AF_INET,SOCK_STREAM,0);
    if (this->connFd==-1)
    {
        cout<<"创建失败"<<endl;
    }
    
}

TcpSocket::TcpSocket(int connFd)
{
    this->connFd=connFd;
}

TcpSocket::~TcpSocket()
{
    // if (this->connFd!=-1)
    // {
    //     close(this->connFd);
    // }
    
}

void TcpSocket::connectServe(string ip, int port, int timeout)
{
    sockaddr_in serverAdd;
    int addsize=sizeof(sockaddr_in);
    serverAdd.sin_family=AF_INET;
    serverAdd.sin_port=htons(port);
    serverAdd.sin_addr.s_addr=inet_addr(ip.c_str());

    int retVal=connect(this->connFd,(sockaddr*)&serverAdd,addsize);
    if (retVal==-1)
    {
        cout<<"链接失败"<<endl;
    }
    
}

int TcpSocket::sendMag(Message *message,int timeout)
{
    return sendMessage(this->connFd,message);
}

Message* TcpSocket::receiveMag(int timeout)
{
    // Message* msg = receiveMessage(this->connFd);
    // if (msg == NULL) {
    //     return NULL; // 处理连接关闭
    // }
    // return msg;
    return receiveMessage(this->connFd);
}

int TcpSocket::getConnFd()
{
    return this->connFd;
}
